package com.speily.web.utils;

import com.speily.web.filter.FilterChain;
import com.speily.web.http.Request;
import com.speily.web.http.Response;
import com.speily.web.servlet.HttpServlet;
import com.speily.web.Mytomcat;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @Auther: SPL
 * @Date: 2019-07-03 11:17
 * @Description:
 */
public class SocketProcess extends Thread{

    protected Socket socket;

    public SocketProcess(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            Request request = new Request(socket.getInputStream());
            Response response = new Response(socket.getOutputStream());

            //从映射中找
            System.out.println("-----查找映射："+request.getUrl());
            String servelName = (String) Mytomcat.servletMapping.get(request.getUrl());
            System.out.println("-----找到映射：" + servelName);

            String header = Response.responseHeader;//默认响应200

            if(servelName!=null && !servelName.equals("")) {

                //映射有的话找到对应的对象
                HttpServlet servlet = (HttpServlet) Mytomcat.servlet.get(servelName);

                this.doFilter(request, response, servlet);//执行过滤器

                if(servlet!=null) {

                    servlet.service(request, response);
                }else {
                    header = Response.resp404;//响应404
                    response.setWirte("404！\n -----找不到对应的servlet");
                    System.out.println("-----找不到对应的servlet");
                }

            }else {
                header = Response.resp404;//响应404
                response.setWirte("404！\n 找不到对应的servletMapping");
                System.out.println("-----找不到对应的servletMapping");
            }

            String res = header + response.getWirte();
            OutputStream outputStream = socket.getOutputStream();

            outputStream.write(res.getBytes("GBK"));
            outputStream.flush();
            outputStream.close();

        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void doFilter(Request request,Response response, HttpServlet servlet) throws IOException {
        //执行拦截 Filter
        FilterChain filterChain = new FilterChain();
        filterChain.setServlet(servlet);

//        filterChain.addFilter();
//        filterChain.addFilter(new TestOneFilter());

        filterChain.doFilter(request, response);
    }

}
